package com.dbflow5.paging;

import com.dbflow5.TestDatabase;
import com.dbflow5.TestExtensions;
import com.dbflow5.config.FlowManager;
import com.dbflow5.models.SimpleModel_Table;
import com.dbflow5.query.From;
import com.dbflow5.query.SQLite;
import com.dbflow5.BaseUnitTest;
import com.dbflow5.models.SimpleTestModels;
import com.dbflow5.query.Set;
import com.dbflow5.structure.Model;
import org.junit.Assert;
import org.junit.Test;

public class QueryDataSourceTest extends BaseUnitTest {
    @Test
    public void testLoadInitialParams() {
        FlowManager.database(TestDatabase.class, db -> {
            for (int i = 0; i < 100; i++) {
                Model.save(SimpleTestModels.SimpleModel.class, new SimpleTestModels.SimpleModel(String.valueOf(i)), db);
            }

            QueryDataSource.Factory<SimpleTestModels.SimpleModel, From<SimpleTestModels.SimpleModel>> factory = QueryDataSource.toDataSourceFactory(SQLite.select().from(SimpleTestModels.SimpleModel.class), db);

            PagedList.Config config = new PagedList.Config.Builder()
                    .setPageSize(3)
                    .setPrefetchDistance(6)
                    .setEnablePlaceholders(true).build();

            PagedList<SimpleTestModels.SimpleModel> list = new PagedList.Builder<>(factory.create(), config)
                    .setFetchExecutor(Runnable::run)
                    .setNotifyExecutor(Runnable::run)
                    .build();

            Assert.assertEquals(100, list.size());

            for (int index = 0; index < list.size(); index++) {
                SimpleTestModels.SimpleModel simpleModel = list.get(index);

                list.loadAround(index);
                Assert.assertEquals(index, Integer.parseInt(simpleModel.name));

                // assert we don't run over somehow.
                Assert.assertTrue(index < 100);
            }

            return null;
        });
    }

    @Test
    public void testThrowsErrorOnInvalidType() {
        FlowManager.database(TestDatabase.class, db -> {
            TestExtensions.assertThrowsException(IllegalArgumentException.class, (unused) -> {
                Set<SimpleTestModels.SimpleModel> simpleModel = SQLite.update(SimpleTestModels.SimpleModel.class).set(SimpleModel_Table.name.eq("name"));
                QueryDataSource.toDataSourceFactory(simpleModel, db).create();
                return null;
            });
            return null;
        });
    }
}
